/**
 * 双击缩放Hook
 * Story 5: Task 5 - 双击缩放功能
 */

import { useState, useRef, useCallback } from 'react'
import { useSpring } from '@react-spring/web'
import { useHapticFeedback } from './useHapticFeedback'
import { useGestureConflictHandler } from './useGestureConflictHandler'

interface DoubleTapZoomOptions {
  maxScale?: number
  minScale?: number
  doubleTapThreshold?: number
  enabled?: boolean
}

/**
 * 双击缩放Hook
 * 提供双击放大/缩小功能，支持拖动查看
 */
export const useDoubleTapZoom = ({
  maxScale = 2,
  minScale = 1,
  doubleTapThreshold = 300,
  enabled = true,
}: DoubleTapZoomOptions = {}) => {
  const [scale, setScale] = useState(minScale)
  const lastTapRef = useRef(0)
  const { trigger: triggerHaptic } = useHapticFeedback()
  const { startGesture, endGesture, canStartGesture } = useGestureConflictHandler()

  const [springProps, api] = useSpring(() => ({
    scale: minScale,
    x: 0,
    y: 0,
    config: { tension: 300, friction: 30 },
  }))

  const handleDoubleTap = useCallback(
    (e: React.TouchEvent | React.MouseEvent) => {
      if (!enabled) return

      const now = Date.now()
      const timeSinceLastTap = now - lastTapRef.current

      if (timeSinceLastTap < doubleTapThreshold && timeSinceLastTap > 0) {
        // 双击检测成功
        if (!canStartGesture('doubleTap')) {
          return
        }

        startGesture('doubleTap')

        const newScale = scale === minScale ? maxScale : minScale

        setScale(newScale)
        api.start({
          scale: newScale,
          x: newScale === minScale ? 0 : undefined,
          y: newScale === minScale ? 0 : undefined,
        })

        // 触觉反馈
        triggerHaptic('light')

        // 短暂延迟后结束手势
        setTimeout(() => {
          endGesture('doubleTap')
        }, 100)

        // 重置计时器
        lastTapRef.current = 0
      } else {
        lastTapRef.current = now
      }
    },
    [
      enabled,
      scale,
      minScale,
      maxScale,
      doubleTapThreshold,
      api,
      triggerHaptic,
      startGesture,
      endGesture,
      canStartGesture,
    ]
  )

  /**
   * 重置缩放
   */
  const reset = useCallback(() => {
    setScale(minScale)
    api.start({
      scale: minScale,
      x: 0,
      y: 0,
    })
  }, [minScale, api])

  /**
   * 设置缩放级别
   */
  const setZoom = useCallback(
    (newScale: number) => {
      const clampedScale = Math.max(minScale, Math.min(maxScale, newScale))
      setScale(clampedScale)
      api.start({
        scale: clampedScale,
        x: clampedScale === minScale ? 0 : undefined,
        y: clampedScale === minScale ? 0 : undefined,
      })
    },
    [minScale, maxScale, api]
  )

  return {
    scale,
    springProps,
    handleDoubleTap,
    reset,
    setZoom,
    isZoomed: scale > minScale,
  }
}
